<template>
	<view class="calendar-container">
		<!-- 顶部统计卡片 -->
		<view class="stats-section">
			<view class="stat-card">
				<view class="stat-number">{{todayMeetings.length}}</view>
				<view class="stat-label">今日会议</view>
			</view>
			<view class="stat-card">
				<view class="stat-number">{{weekMeetings.length}}</view>
				<view class="stat-label">本周会议</view>
			</view>
			<view class="stat-card">
				<view class="stat-number">{{ongoingMeetings.length}}</view>
				<view class="stat-label">进行中</view>
			</view>
		</view>
		
		<!-- 日历头部 -->
		<view class="calendar-header">
			<view class="header-content">
				<view class="month-selector">
					<view class="arrow-btn" @click="prevMonth">
						<image class="arrow" src="/static/right.png" mode="aspectFit" style="transform: rotate(180deg);"></image>
					</view>
					<view class="current-month">
						<text class="month-text">{{currentYear}}年{{currentMonth}}月</text>
					</view>
					<view class="arrow-btn" @click="nextMonth">
						<image class="arrow" src="/static/right.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="today-btn" @click="goToToday">
					<text>今天</text>
				</view>
			</view>
		</view>
		
		<!-- 日历主体 -->
		<view class="calendar-body">
			<!-- 月份背景文字 -->
			<view class="month-background">
				<text class="month-bg-text">{{currentMonth}}月</text>
			</view>
			
			<view class="weekdays">
				<text class="weekday" v-for="day in weekdays" :key="day">{{day}}</text>
			</view>
			
			<view class="days">
				<view 
					class="day-item" 
					v-for="(day, index) in days" 
					:key="index"
					:class="getDayClass(day)" 
					@click="selectDate(day)"
				>
					<view class="day-content">
						<text class="day-number">{{day.day}}</text>
						<view class="meeting-indicators" v-if="day.meetingCount > 0">
							<view class="meeting-dot" v-for="i in Math.min(day.meetingCount, 3)" :key="i"></view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 会议列表 -->
		<view class="meeting-list" v-if="selectedDateMeetings.length > 0 || isLoadingMeetings">
			<view class="list-header">
				<view class="date-info">
					<text class="date-title">{{formatSelectedDate(selectedDate)}}</text>
					<text class="meeting-count" v-if="!isLoadingMeetings">{{selectedDateMeetings.length}}个会议</text>
					<text class="meeting-count" v-else>加载中...</text>
				</view>
				<view class="list-actions">
					<view class="action-btn" @click="addMeeting" v-if="canAddMeeting">
						<text>添加会议</text>
					</view>
				</view>
			</view>
			
			<!-- 加载状态 -->
			<view class="loading-state" v-if="isLoadingMeetings">
				<view class="loading-icon">⏳</view>
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 会议列表 -->
			<view class="meeting-items" v-else>
				<view class="meeting-item" v-for="(meeting, index) in selectedDateMeetings" :key="index">
					<view class="meeting-main" @click="viewMeeting(meeting)">
						<view class="meeting-time">
							<text class="time-text">{{meeting.startTime}}</text>
							<view class="meeting-status" :class="getMeetingStatusClass(meeting)">
								<text>{{meeting.statusText}}</text>
							</view>
						</view>
						<view class="meeting-content">
							<view class="meeting-header">
								<text class="meeting-title">{{meeting.title}}</text>
							</view>
							<view class="meeting-details">
								<view class="detail-item">
									<image class="detail-icon" src="/static/time.png" mode="aspectFit"></image>
									<text class="detail-text">{{meeting.startTime}} - {{meeting.endTime}}</text>
								</view>
								<view class="detail-item">
									<image class="detail-icon" src="/static/room.png" mode="aspectFit"></image>
									<text class="detail-text">{{meeting.room}}</text>
								</view>
								<view class="detail-item" v-if="meeting.organizer">
									<image class="detail-icon" src="/static/user.png" mode="aspectFit"></image>
									<text class="detail-text">召集人：{{meeting.organizer}}</text>
								</view>
								<view class="detail-item" v-if="meeting.reserver">
									<image class="detail-icon" src="/static/user.png" mode="aspectFit"></image>
									<text class="detail-text">预约人：{{meeting.reserver}}</text>
								</view>
								<view class="detail-item" v-if="meeting.ensure === 1 && canViewMeetingSupport(meeting)">
									<image class="detail-icon" src="/static/baozhang.png" mode="aspectFit"></image>
									<text class="detail-text">需要会议保障</text>
								</view>
								<view class="detail-item" v-if="meeting.need_branch_office === 'yes'">
									<image class="detail-icon" src="/static/share.png" mode="aspectFit"></image>
									<text class="detail-text">到分局：{{meeting.selected_branches || '已选择分局'}}</text>
								</view>
							</view>
						</view>
						<view class="meeting-arrow">
							<image src="/static/right.png" mode="aspectFit"></image>
						</view>
					</view>
					<!-- 管理员操作按钮 -->
					<view class="meeting-actions" v-if="isAdmin && (meeting.status === 'pending' || meeting.status === 'upcoming')">
						<view class="action-btn edit-btn" @click.stop="editMeeting(meeting)">
							<text class="btn-text">修改</text>
						</view>
						<view class="action-btn reject-btn" @click.stop="rejectMeeting(meeting)">
							<text class="btn-text">审核拒绝</text>
						</view>
					</view>
					<!-- 用户自己创建的操作按钮 -->
					<view class="meeting-actions" v-if="!isAdmin && isMyMeeting(meeting) && isMeetingNotStarted(meeting)">
						<view class="action-btn edit-btn" @click.stop="editMeeting(meeting)">
							<text class="btn-text">修改</text>
						</view>
						<view class="action-btn cancel-btn" @click.stop="cancelMeeting(meeting)">
							<text class="btn-text">取消</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else-if="selectedDate">
			<!-- <view class="empty-icon">📅</view> -->
			<text class="empty-title">{{formatSelectedDate(selectedDate)}}</text>
			<text class="empty-text">暂无会议安排</text>
			<view class="empty-action" @click="addMeeting" v-if="canAddMeeting">
				<text>添加会议</text>
			</view>
		</view>
	</view>
</template>

<script>
import api, { handleApiError } from '@/utils/api.js'

export default {
	data() {
		return {
			weekdays: ['日', '一', '二', '三', '四', '五', '六'],
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth() + 1,
			days: [],
			selectedDate: '',
			selectedDateMeetings: [],
			isLoadingMeetings: false,
			isLoadingMonthData: false,
			meetings: [], // 存储当前月份的所有会议数据
			roomMap: {}, // 会议室映射，key为pid，value为会议室名称
			userMap: {}, // 用户映射，key为userId，value为用户信息
			roomList: [], // 会议室列表
			currentUser: null, // 当前用户信息
			isAdmin: false // 是否是管理员
		}
	},
	async mounted() {
		// 检查是否登录
		const token = uni.getStorageSync('token');
		const isLoggedIn = !!token;
		
		// 如果已登录，加载基础数据
		if (isLoggedIn) {
			await Promise.all([
				this.loadRoomList(),
				this.loadUserList(),
				this.loadCurrentUser()
			]);
		}

		// 默认选中今天
		const today = this.formatDate(new Date());
		this.selectedDate = today;
		
		// 初始化时加载会议数据（确保统计卡片有数据）
		await this.loadMonthMeetings();
		this.generateCalendar();
		if (this.selectedDate) {
			this.loadMeetingsByDate(this.selectedDate);
		}
		// iOS兼容性：确保computed属性更新
		this.$nextTick(() => {
			this.$forceUpdate();
		});
	},
	async onShow() {
		// 检查是否登录
		const token = uni.getStorageSync('token');
		const isLoggedIn = !!token;
		
		// 如果已登录，刷新用户信息（确保管理员状态是最新的）
		if (isLoggedIn) {
			await this.loadCurrentUser();
		} else {
			// 未登录时，重置用户相关状态
			this.currentUser = null;
			this.isAdmin = false;
		}
		
		// 页面显示时，加载选中日期的会议列表（未登录也可以查看）
		if (this.selectedDate) {
			this.loadMeetingsByDate(this.selectedDate);
		} else {
			// 如果没有选中日期，默认选中今天并加载
			const today = this.formatDate(new Date());
			this.selectedDate = today;
			this.loadMeetingsByDate(today);
		}

		// 加载当前月份的会议数据（未登录也可以查看）
		await this.loadMonthMeetings();
		// 生成日历
		this.generateCalendar();
		// iOS兼容性：确保computed属性更新
		this.$nextTick(() => {
			this.$forceUpdate();
		});
	},
	methods: {
		// 格式化时间，只显示时分
		formatTime(time) {
			if (!time) return '09:00';
			// 如果包含秒，去掉秒
			if (time.includes(':') && time.split(':').length === 3) {
				return time.substring(0, 5);
			}
			return time;
		},
		
		// 加载会议室列表
		async loadRoomList() {
			try {
				const response = await api.getRoomList();
				if (response && response.code === 200) {
					const rooms = response.rows || [];
					// 保存会议室列表
					this.roomList = rooms;
					// 构建会议室映射
					this.roomMap = {};
					rooms.forEach(room => {
						const roomId = room.roomId || room.id;
						const roomName = room.roomName || room.name || '未知会议室';
						this.roomMap[roomId] = roomName;
					});
				}
			} catch (error) {
				console.error('获取会议室列表错误:', error);
				// 如果获取失败，不影响会议列表的显示
			}
		},
		
		// 加载用户列表
		async loadUserList() {
			try {
				const response = await api.getUserList();
				if (response && response.code === 200) {
					const users = response.rows || [];
					// 构建用户映射
					this.userMap = {};
					users.forEach(user => {
						const userId = user.userId;
						this.userMap[userId] = {
							nickName: user.nickName || user.userName,
							userName: user.userName
						};
					});
				}
			} catch (error) {
				console.error('获取用户列表错误:', error);
				// 如果获取失败，不影响会议列表的显示
			}
		},
		
		// 加载当前用户信息
		async loadCurrentUser() {
			try {
				const storedUserInfo = uni.getStorageSync('userInfo');
				if (storedUserInfo && storedUserInfo.userId) {
					this.currentUser = {
						userId: storedUserInfo.userId,
						userName: storedUserInfo.userName || storedUserInfo.username,
						nickName: storedUserInfo.nickName || storedUserInfo.nickname
					};
					// 判断是否是管理员
					this.isAdmin = this.checkIsAdmin(storedUserInfo);
				}
				
				// 从接口获取最新用户信息
				const response = await api.getUserInfo();
				if (response && response.code === 200 && response.user) {
					const user = response.user;
					this.currentUser = {
						userId: user.userId,
						userName: user.userName,
						nickName: user.nickName
					};
					// 判断是否是管理员
					this.isAdmin = this.checkIsAdmin(user);
					// 更新本地存储
					uni.setStorageSync('userInfo', {
						userId: this.currentUser.userId,
						userName: this.currentUser.userName,
						nickName: this.currentUser.nickName,
						roles: user.roles || []
					});
				}
			} catch (error) {
				console.error('获取当前用户信息错误:', error);
				// 如果获取失败，尝试使用本地存储的信息
				const storedUserInfo = uni.getStorageSync('userInfo');
				if (storedUserInfo && storedUserInfo.userId) {
					this.currentUser = {
						userId: storedUserInfo.userId,
						userName: storedUserInfo.userName || storedUserInfo.username,
						nickName: storedUserInfo.nickName || storedUserInfo.nickname
					};
					this.isAdmin = this.checkIsAdmin(storedUserInfo);
				} else {
					// 如果都没有，说明未登录
					this.currentUser = null;
					this.isAdmin = false;
				}
			}
		},
		
		// 判断是否是管理员
		checkIsAdmin(user) {
			if (!user) return false;
			// 检查roles数组中是否包含'admin'字符串
			const roles = user.roles || [];
			return roles.some(role => {
				if (typeof role === 'string') {
					return role.includes('admin');
				} else if (role && role.roleKey) {
					return role.roleKey.includes('admin');
				}
				return false;
			});
		},
		
		// 判断是否可以查看会议保障信息
		canViewMeetingSupport(meeting) {
			if (!this.currentUser || !meeting) return false;
			// 管理员可以查看
			if (this.isAdmin) return true;
			// 创建者可以查看
			if (meeting.reservedby && this.currentUser.userId && meeting.reservedby === this.currentUser.userId) {
				return true;
			}
			return false;
		},
		
		// 判断是否是用户自己创建的会议
		isMyMeeting(meeting) {
			if (!this.currentUser || !meeting) return false;
			// 检查创建者ID是否匹配当前用户ID
			if (meeting.reservedby && this.currentUser.userId && meeting.reservedby === this.currentUser.userId) {
				return true;
			}
			return false;
		},
		
		// 判断会议是否未开始
		isMeetingNotStarted(meeting) {
			if (!meeting) return false;
			// 待审核状态（state === '1'）可以修改和取消
			if (meeting.state === '1') {
				return true;
			}
			// 已通过但未开始（state === '2' 且 status === 'upcoming'）可以修改和取消
			if (meeting.state === '2' && meeting.status === 'upcoming') {
				return true;
			}
			return false;
		},
		
		// 加载当前月份的会议数据
		async loadMonthMeetings() {
			this.isLoadingMonthData = true;
			
			try {
				// 计算月份的开始和结束日期
				const startDate = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-01`;
				const lastDay = new Date(this.currentYear, this.currentMonth, 0).getDate();
				const endDate = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
				
				// 只查询审核通过的会议（state === '2'）
				const params = {
					state: '2'
				};
				const response = await api.getMeetingsByMonth(startDate, endDate, params);
				
				if (response && response.code === 200) {
					const meetings = response.rows || [];
					// 转换数据格式（只显示审核通过的会议）
					const monthMeetings = meetings
						.map(meeting => ({
							id: meeting.id,
							date: meeting.thedate,
							title: meeting.meetingtitle || '会议',
							startTime: this.formatTime(meeting.startTime),
							endTime: this.formatTime(meeting.endTime),
							room: this.roomMap[meeting.pid] || '未知会议室',
							roomId: meeting.pid,
							status: this.getMeetingStatusFromState(meeting),
							statusText: this.getStatusTextByStatus(this.getMeetingStatusFromState(meeting), meeting.state),
							organizer: this.userMap[meeting.convener]?.nickName || '未知',
							organizerId: meeting.convener,
							reserver: this.userMap[meeting.reservedby]?.nickName || '未知',
							reserverId: meeting.reservedby,
							participants: meeting.content || '',
							remark: meeting.remark || '',
							ensure: meeting.ensure || 0,
							need_branch_office: meeting.need_branch_office === 1 ? 'yes' : 'no',
							selected_branches: meeting.selected_branches || '',
							state: meeting.state,
							yuanyin: meeting.yuanyin || '',
							reservedby: meeting.reservedby || '' // 创建者ID
						}));
					
					// 为了确保统计卡片有数据，同时加载本周的数据
					await this.loadWeekMeetingsForStats(monthMeetings);
					
					// 重新生成日历以显示会议标记
					this.generateCalendar();
				} else {
					console.error('获取会议列表失败:', response.msg);
					this.meetings = [];
					// 即使月份数据加载失败，也尝试加载本周数据
					await this.loadWeekMeetingsForStats([]);
				}
			} catch (error) {
				console.error('获取会议列表错误:', error);
				this.meetings = [];
				// 即使出错，也尝试加载本周数据
				try {
					await this.loadWeekMeetingsForStats([]);
				} catch (e) {
					console.error('加载本周数据失败:', e);
				}
			} finally {
				this.isLoadingMonthData = false;
			}
		},
		
		// 加载本周的会议数据（用于统计卡片）
		async loadWeekMeetingsForStats(existingMeetings = []) {
			try {
				const today = new Date();
				const weekStart = new Date(today);
				weekStart.setDate(today.getDate() - today.getDay());
				weekStart.setHours(0, 0, 0, 0);
				const weekEnd = new Date(weekStart);
				weekEnd.setDate(weekStart.getDate() + 6);
				weekEnd.setHours(23, 59, 59, 999);
				
				const startDateStr = this.formatDate(weekStart);
				const endDateStr = this.formatDate(weekEnd);
				
				// 只查询审核通过的会议（state === '2'）
				const params = {
					state: '2'
				};
				const response = await api.getMeetingsByMonth(startDateStr, endDateStr, params);
				
				if (response && response.code === 200) {
					const weekMeetings = response.rows || [];
					// 转换数据格式
					const formattedWeekMeetings = weekMeetings
						.map(meeting => ({
							id: meeting.id,
							date: meeting.thedate,
							title: meeting.meetingtitle || '会议',
							startTime: this.formatTime(meeting.startTime),
							endTime: this.formatTime(meeting.endTime),
							room: this.roomMap[meeting.pid] || '未知会议室',
							roomId: meeting.pid,
							status: this.getMeetingStatusFromState(meeting),
							statusText: this.getStatusTextByStatus(this.getMeetingStatusFromState(meeting), meeting.state),
							organizer: this.userMap[meeting.convener]?.nickName || '未知',
							organizerId: meeting.convener,
							reserver: this.userMap[meeting.reservedby]?.nickName || '未知',
							reserverId: meeting.reservedby,
							participants: meeting.content || '',
							remark: meeting.remark || '',
							ensure: meeting.ensure || 0,
							need_branch_office: meeting.need_branch_office === 1 ? 'yes' : 'no',
							selected_branches: meeting.selected_branches || '',
							state: meeting.state,
							yuanyin: meeting.yuanyin || '',
							reservedby: meeting.reservedby || ''
						}));
					
					// 合并数据，去重（基于id）
					const meetingMap = new Map();
					// 先添加现有会议（当前月份的）
					existingMeetings.forEach(meeting => {
						meetingMap.set(meeting.id, meeting);
					});
					// 再添加本周会议（会覆盖重复的，确保数据最新）
					formattedWeekMeetings.forEach(meeting => {
						meetingMap.set(meeting.id, meeting);
					});
					
					// 合并后的数据：当前月份 + 本周不在当前月份的数据
					// 使用新数组确保Vue响应式系统能正确检测变化（iOS兼容性）
					const mergedMeetings = Array.from(meetingMap.values());
					// 直接赋值新数组，确保Vue能检测到变化
					this.meetings = mergedMeetings;
					// iOS兼容性：使用nextTick确保DOM和computed属性更新
					this.$nextTick(() => {
						// 强制触发视图更新（确保computed属性重新计算）
						this.$forceUpdate();
					});
				}
			} catch (error) {
				console.error('加载本周会议数据错误:', error);
				// 如果加载失败，至少保留现有数据
				if (existingMeetings.length > 0) {
					this.meetings = existingMeetings;
				} else {
					// 如果现有数据也为空，确保 meetings 至少是空数组（避免 undefined）
					this.meetings = [];
				}
			}
		},
		
		// 根据state字段获取会议状态
		getMeetingStatusFromState(meeting) {
			// state: 1待审核, 2已通过, 3不通过, 4已取消
			if (meeting.state === '4') {
				return 'cancelled'; // 已取消
			}
			if (meeting.state === '3') {
				return 'rejected'; // 不通过
			}
			if (meeting.state === '1') {
				return 'pending'; // 待审核
			}
			if (meeting.state === '2') {
				// 已通过，根据时间判断是即将开始、进行中还是已完成
				return this.getMeetingStatusByTime(meeting);
			}
			return 'pending';
		},
		
		// 根据时间判断会议状态
		getMeetingStatusByTime(meeting) {
			const now = new Date();
			const meetingDate = new Date(meeting.thedate);
			const startTime = meeting.startTime;
			const endTime = meeting.endTime;
			
			if (startTime && endTime) {
				const [startHour, startMin] = startTime.split(':').map(Number);
				const [endHour, endMin] = endTime.split(':').map(Number);
				const startDateTime = new Date(meetingDate);
				startDateTime.setHours(startHour, startMin, 0, 0);
				const endDateTime = new Date(meetingDate);
				endDateTime.setHours(endHour, endMin, 0, 0);
				
				if (now < startDateTime) {
					return 'upcoming'; // 即将开始
				} else if (now >= startDateTime && now <= endDateTime) {
					return 'ongoing'; // 进行中
				} else {
					return 'completed'; // 已完成
				}
			}
			
			return 'upcoming';
		},
		
		// 根据state获取状态文本
		getStatusTextFromState(state) {
			const statusMap = {
				'1': '待审核',
				'2': '已通过',
				'3': '不通过',
				'4': '已取消'
			};
			return statusMap[state] || '未知';
		},
		
		// 按日期查询会议列表
		async loadMeetingsByDate(date) {
			if (!date) return;
			
			this.isLoadingMeetings = true;
			
			try {
				// 只查询审核通过的会议（state === '2'）
				const params = {
					state: '2'
				};
				const response = await api.getMeetingsByDate(date, params);
				
				if (response && response.code === 200) {
					const meetings = response.rows || [];
					// 转换数据格式（只显示审核通过的会议）
					this.selectedDateMeetings = meetings
						.map(meeting => ({
							id: meeting.id,
							date: date,
							title: meeting.meetingtitle || '会议',
							startTime: this.formatTime(meeting.startTime),
							endTime: this.formatTime(meeting.endTime),
							room: this.roomMap[meeting.pid] || '未知会议室',
							roomId: meeting.pid,
							status: this.getMeetingStatusFromState(meeting),
							statusText: this.getStatusTextByStatus(this.getMeetingStatusFromState(meeting), meeting.state),
							organizer: this.userMap[meeting.convener]?.nickName || '未知',
							organizerId: meeting.convener,
							reserver: this.userMap[meeting.reservedby]?.nickName || '未知',
							reserverId: meeting.reservedby,
							participants: meeting.content || '',
							remark: meeting.remark || '',
							ensure: meeting.ensure || 0,
							need_branch_office: meeting.need_branch_office === 1 ? 'yes' : 'no',
							selected_branches: meeting.selected_branches || '',
							state: meeting.state,
							yuanyin: meeting.yuanyin || '',
							reservedby: meeting.reservedby || '' // 创建者ID
						}))
						.sort((a, b) => {
							// 按开始时间升序排序（早的在前）
							const timeA = a.startTime || '00:00';
							const timeB = b.startTime || '00:00';
							return timeA.localeCompare(timeB);
						});
				} else {
					console.error('获取会议列表失败:', response.msg);
					this.selectedDateMeetings = [];
				}
			} catch (error) {
				console.error('获取会议列表错误:', error);
				this.selectedDateMeetings = [];
			} finally {
				this.isLoadingMeetings = false;
			}
		},
		
		// 根据状态获取状态文本（用于显示）
		getStatusTextByStatus(status, state) {
			// 取消优先
			if (state === '4') {
				return '已取消';
			}
			// 如果state是3（不通过），显示不通过
			if (state === '3') {
				return '不通过';
			}
			// 如果state是1（待审核），显示待审核
			if (state === '1') {
				return '待审核';
			}
			// 如果state是2（已通过），根据时间状态显示
			if (state === '2') {
				const statusMap = {
					'upcoming': '即将开始',
					'ongoing': '进行中',
					'completed': '已完成'
				};
				return statusMap[status] || '已通过';
			}
			return '未知';
		},
		
		generateCalendar() {
			const year = this.currentYear
			const month = this.currentMonth
			const firstDay = new Date(year, month - 1, 1)
			const lastDay = new Date(year, month, 0)
			const startDate = new Date(firstDay)
			startDate.setDate(startDate.getDate() - firstDay.getDay())
			
			this.days = []
			
			for (let i = 0; i < 42; i++) {
				const currentDate = new Date(startDate)
				currentDate.setDate(startDate.getDate() + i)
				
				const dayObj = {
					day: currentDate.getDate(),
					date: this.formatDate(currentDate),
					isCurrentMonth: currentDate.getMonth() === month - 1,
					isToday: this.isToday(currentDate),
					hasMeeting: this.hasMeeting(this.formatDate(currentDate)),
					meetingCount: this.getMeetingCount(this.formatDate(currentDate))
				}
				
				this.days.push(dayObj)
			}
		},
		formatDate(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		isToday(date) {
			const today = new Date()
			return date.toDateString() === today.toDateString()
		},
		hasMeeting(date) {
			return this.meetings.some(meeting => meeting.date === date)
		},
		
		getMeetingCount(date) {
			return this.meetings.filter(meeting => meeting.date === date).length
		},
		
		formatSelectedDate(dateStr) {
			if (!dateStr) return '';
			const date = new Date(dateStr);
			const today = new Date();
			const tomorrow = new Date(today);
			tomorrow.setDate(today.getDate() + 1);
			
			if (date.toDateString() === today.toDateString()) {
				return '今天';
			} else if (date.toDateString() === tomorrow.toDateString()) {
				return '明天';
			} else {
				const month = date.getMonth() + 1;
				const day = date.getDate();
				return `${month}月${day}日`;
			}
		},
		getDayClass(day) {
			const classes = []
			if (!day.isCurrentMonth) {
				classes.push('other-month')
			}
			if (day.isToday) {
				classes.push('today')
			}
			if (day.hasMeeting) {
				classes.push('has-meeting')
			}
			if (this.selectedDate === day.date) {
				classes.push('selected')
			}
			return classes.join(' ')
		},
		async selectDate(day) {
			// 设置选中的日期
			this.selectedDate = day.date
			
			// 从日期字符串中提取年月
			const dateParts = day.date.split('-')
			const selectedYear = parseInt(dateParts[0])
			const selectedMonth = parseInt(dateParts[1])
			
			// 如果点击的是其他月份的日期，自动切换到该月份
			if (!day.isCurrentMonth || this.currentYear !== selectedYear || this.currentMonth !== selectedMonth) {
				this.currentYear = selectedYear
				this.currentMonth = selectedMonth
				// 重新生成日历（先更新显示）
				this.generateCalendar()
				// 加载新月份的会议数据
				await this.loadMonthMeetings()
			}
			
			// 使用接口查询选中日期的会议
			this.loadMeetingsByDate(day.date)
		},
		prevMonth() {
			if (this.currentMonth === 1) {
				this.currentYear--
				this.currentMonth = 12
			} else {
				this.currentMonth--
			}
			// 加载新月份的会议数据
			this.loadMonthMeetings()
			this.generateCalendar()
		},
		nextMonth() {
			if (this.currentMonth === 12) {
				this.currentYear++
				this.currentMonth = 1
			} else {
				this.currentMonth++
			}
			// 加载新月份的会议数据
			this.loadMonthMeetings()
			this.generateCalendar()
		},
		
		goToToday() {
			const today = new Date()
			const todayStr = this.formatDate(today)
			
			// 更新当前年月为今天
			const newYear = today.getFullYear()
			const newMonth = today.getMonth() + 1
			
			// 如果月份改变，需要重新加载数据
			if (this.currentYear !== newYear || this.currentMonth !== newMonth) {
				this.currentYear = newYear
				this.currentMonth = newMonth
				// 加载新月份的会议数据
				this.loadMonthMeetings()
			}
			
			// 重新生成日历
			this.generateCalendar()
			
			// 选中今天并使用接口查询今天的会议
			this.selectedDate = todayStr
			this.loadMeetingsByDate(todayStr)
		},
		
		async addMeeting() {
			// 检查登录状态
			if (!this.currentUser) {
				uni.showModal({
					title: '提示',
					content: '添加会议需要先登录，是否前往登录？',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/index'
							});
						}
					}
				});
				return;
			}
			
			// 如果有选中的日期，直接跳转到预约页面并传递日期
			if (this.selectedDate) {
				// 如果有会议室列表，使用第一个会议室
				if (this.roomList && this.roomList.length > 0) {
					const firstRoom = this.roomList[0];
					const roomId = firstRoom.roomId || firstRoom.id;
					const roomName = firstRoom.roomName || firstRoom.name || '未知会议室';
					// 直接跳转到预约页面，传递日期和会议室信息
					uni.navigateTo({
						url: `/pages/enroll/predetermined?id=${roomId}&title=${encodeURIComponent(roomName)}&date=${this.selectedDate}`
					});
				} else {
					// 如果没有会议室列表，先加载
					await this.loadRoomList();
					if (this.roomList && this.roomList.length > 0) {
						const firstRoom = this.roomList[0];
						const roomId = firstRoom.roomId || firstRoom.id;
						const roomName = firstRoom.roomName || firstRoom.name || '未知会议室';
						uni.navigateTo({
							url: `/pages/enroll/predetermined?id=${roomId}&title=${encodeURIComponent(roomName)}&date=${this.selectedDate}`
						});
					} else {
						// 如果没有会议室，跳转到会议室列表页面
						uni.switchTab({
							url: '/pages/enroll/index'
						});
					}
				}
			} else {
				// 如果没有选中日期，跳转到会议室列表页面
				uni.switchTab({
					url: '/pages/enroll/index'
				});
			}
		},
		
		// 获取会议状态样式类
		getMeetingStatusClass(meeting) {
			// 已取消
			if (meeting.state === '4') {
				return 'cancelled';
			}
			// 如果不通过，显示为rejected样式
			if (meeting.state === '3') {
				return 'rejected';
			}
			// 如果待审核，显示为pending样式
			if (meeting.state === '1') {
				return 'pending';
			}
			// 如果已通过，根据时间状态显示
			if (meeting.state === '2') {
				return meeting.status || 'upcoming';
			}
			return 'pending';
		},
		
		viewMeeting(meeting) {
			let content = `时间：${meeting.startTime} - ${meeting.endTime}\n会议室：${meeting.room}\n状态：${meeting.statusText}`;
			
			if (meeting.organizer) {
				content += `\n召集人：${meeting.organizer}`;
			}
			
			if (meeting.reserver) {
				content += `\n预约人：${meeting.reserver}`;
			}
			
			if (meeting.participants) {
				content += `\n参会人员：${meeting.participants}`;
			}
			
			if (meeting.ensure === 1 && this.canViewMeetingSupport(meeting)) {
				content += `\n会议保障：需要`;
			}
			
			// 显示是否到分局信息
			if (meeting.need_branch_office === 'yes') {
				content += `\n是否到分局：是`;
				if (meeting.selected_branches) {
					content += `\n选择的分局：${meeting.selected_branches}`;
				}
			} else {
				content += `\n是否到分局：否`;
			}
			
			if (meeting.remark) {
				content += `\n备注：${meeting.remark}`;
			}
			
			if (meeting.state === '3' && meeting.yuanyin) {
				content += `\n不通过原因：${meeting.yuanyin}`;
			}
			
			if (meeting.state === '4') {
				content += `\n（该预约已取消）`;
			}
			
			uni.showModal({
				title: meeting.title,
				content: content,
				showCancel: false
			})
		},
		
		// 编辑会议（管理员）
		editMeeting(meeting) {
			// 跳转到编辑页面
			uni.navigateTo({
				url: `/pages/enroll/predetermined?editId=${meeting.id}&roomId=${meeting.roomId}`
			});
		},
		
		// 审核拒绝（管理员）
		rejectMeeting(meeting) {
			// 如果已经是拒绝状态，提示
			if (meeting.state === '3') {
				uni.showToast({
					title: '该预约已被拒绝',
					icon: 'none'
				});
				return;
			}
			
			// 如果已取消，提示
			if (meeting.state === '4') {
				uni.showToast({
					title: '已取消的预约不能拒绝',
					icon: 'none'
				});
				return;
			}
			
			// 弹出输入框，让管理员输入拒绝原因
			uni.showModal({
				title: '审核拒绝',
				editable: true,
				placeholderText: '请输入拒绝原因（必填）',
				content: '确定要拒绝此预约吗？',
				success: async (res) => {
					if (res.confirm) {
						const reason = res.content || '';
						if (!reason.trim()) {
							uni.showToast({
								title: '请输入拒绝原因',
								icon: 'none'
							});
							return;
						}
						
						// 显示加载提示
						uni.showLoading({
							title: '处理中...',
							mask: true
						});
						
						try {
							// 调用接口，将状态设置为3（拒绝），并填写拒绝原因
							const response = await api.updateYuyue({
								id: meeting.id,
								state: '3',
								yuanyin: reason.trim()
							});
							
							uni.hideLoading();
							
							if (response && response.code === 200) {
								uni.showToast({
									title: '已拒绝',
									icon: 'success',
									duration: 1500
								});
								
								// 重新加载数据
								setTimeout(() => {
									this.loadMeetingsByDate(this.selectedDate);
									this.loadMonthMeetings();
								}, 500);
							} else {
								uni.showToast({
									title: response?.msg || '操作失败',
									icon: 'none',
									duration: 2000
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error('拒绝预约失败:', error);
							handleApiError(error);
						}
					}
				}
			});
		},
		
		// 取消会议（用户自己创建的）
		async cancelMeeting(meeting) {
			// 检查是否可以取消
			if (!this.isMeetingNotStarted(meeting)) {
				uni.showToast({
					title: '当前状态不可取消',
					icon: 'none'
				});
				return;
			}
			
			// 如果已取消，提示
			if (meeting.state === '4') {
				uni.showToast({
					title: '该预约已取消',
					icon: 'none'
				});
				return;
			}
			
			uni.showModal({
				title: '确认取消',
				content: '确定要取消此预约吗？',
				success: async (res) => {
					if (res.confirm) {
						// 显示加载提示
						uni.showLoading({
							title: '处理中...',
							mask: true
						});
						
						try {
							// 调用接口，将状态设置为4（取消）
							const response = await api.updateYuyue({
								id: meeting.id,
								state: '4'
							});
							
							uni.hideLoading();
							
							if (response && response.code === 200) {
								uni.showToast({
									title: '已取消',
									icon: 'success',
									duration: 1500
								});
								
								// 重新加载数据
								setTimeout(() => {
									this.loadMeetingsByDate(this.selectedDate);
									this.loadMonthMeetings();
								}, 500);
							} else {
								uni.showToast({
									title: response?.msg || '取消失败',
									icon: 'none',
									duration: 2000
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error('取消预约失败:', error);
							handleApiError(error);
						}
					}
				}
			});
		}
	},
	computed: {
		// 判断是否可以添加会议（选中的日期必须是今天或今天之后）
		canAddMeeting() {
			if (!this.selectedDate) return false;
			const today = this.formatDate(new Date());
			const selected = new Date(this.selectedDate);
			const todayDate = new Date(today);
			// 将时间设置为0点，只比较日期
			selected.setHours(0, 0, 0, 0);
			todayDate.setHours(0, 0, 0, 0);
			// 选中的日期必须是今天或今天之后
			return selected >= todayDate;
		},
		todayMeetings() {
			if (!this.meetings || !Array.isArray(this.meetings)) {
				return [];
			}
			const today = this.formatDate(new Date());
			// 由于只请求已通过的会议，这里不需要再过滤state
			const result = this.meetings.filter(meeting => {
				if (!meeting || !meeting.date) return false;
				return meeting.date === today;
			});
			return result;
		},
		weekMeetings() {
			if (!this.meetings || !Array.isArray(this.meetings)) {
				return [];
			}
			const today = new Date();
			const weekStart = new Date(today);
			weekStart.setDate(today.getDate() - today.getDay());
			weekStart.setHours(0, 0, 0, 0);
			const weekEnd = new Date(weekStart);
			weekEnd.setDate(weekStart.getDate() + 6);
			weekEnd.setHours(23, 59, 59, 999);
			
			// 由于只请求已通过的会议，这里不需要再过滤state
			const result = this.meetings.filter(meeting => {
				if (!meeting || !meeting.date) return false;
				// iOS兼容性：使用更安全的日期解析方式
				const dateStr = meeting.date;
				const [year, month, day] = dateStr.split('-').map(Number);
				const meetingDate = new Date(year, month - 1, day);
				meetingDate.setHours(0, 0, 0, 0);
				return meetingDate >= weekStart && meetingDate <= weekEnd;
			});
			return result;
		},
		ongoingMeetings() {
			if (!this.meetings || !Array.isArray(this.meetings)) {
				return [];
			}
			// 统计进行中的会议（由于只请求已通过的会议，这里不需要再过滤state）
			const result = this.meetings.filter(meeting => {
				if (!meeting) return false;
				return meeting.status === 'ongoing';
			});
			return result;
		}
	}
}
</script>

<style scoped>
.calendar-container {
	padding: 30rpx;
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
	min-height: 100vh;
}

/* 统计卡片 */
.stats-section {
	display: flex;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.stat-card {
	flex: 1;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 30rpx 20rpx;
	text-align: center;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.stat-number {
	font-size: 48rpx;
	font-weight: bold;
	color: #2870E5;
	margin-bottom: 10rpx;
}

.stat-label {
	font-size: 24rpx;
	color: #666;
}

/* 日历头部 */
.calendar-header {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.month-selector {
	display: flex;
	align-items: center;
	gap: 30rpx;
}

.arrow-btn {
	width: 60rpx;
	height: 60rpx;
	background: #f8f9fa;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.3s ease;
}

.arrow-btn:active {
	background: #e9ecef;
	transform: scale(0.95);
}

.arrow {
	width: 32rpx;
	height: 32rpx;
}

.current-month {
	text-align: center;
}

.month-text {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	display: block;
}

.year-subtitle {
	font-size: 24rpx;
	color: #999;
}

.today-btn {
	background: #2870E5;
	color: #fff;
	padding: 15rpx 30rpx;
	border-radius: 25rpx;
	font-size: 28rpx;
	cursor: pointer;
	transition: all 0.3s ease;
}

.today-btn:active {
	transform: scale(0.95);
}

/* 日历主体 */
.calendar-body {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	position: relative;
	overflow: hidden;
}

/* 月份背景文字 */
.month-background {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	pointer-events: none;
	z-index: 1;
}

.month-bg-text {
	font-size: 120rpx;
	font-weight: 300;
	color: rgba(40, 112, 229, 0.08);
	text-align: center;
	line-height: 1;
	transform: translateY(-20rpx);
}

.weekdays {
	display: flex;
	margin-bottom: 30rpx;
	position: relative;
	z-index: 2;
}

.weekday {
	width: 14.28%;
	text-align: center;
	font-size: 28rpx;
	color: #666;
	font-weight: 500;
	padding: 20rpx 0;
}

.days {
	display: flex;
	flex-wrap: wrap;
	position: relative;
	z-index: 2;
}

.day-item {
	width: 14.28%;
	height: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	border-radius: 16rpx;
	cursor: pointer;
	transition: all 0.3s ease;
	box-sizing: border-box;
}

.day-item:active {
	transform: scale(0.95);
}

.day-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
	width: 100%;
	height: 100%;
}

.day-number {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
	line-height: 1;
	flex-shrink: 0;
}

.other-month .day-number {
	color: #ccc;
}

.today {
	position: relative;
	border-radius: 16rpx;
}

.today .day-number {
	color: #5B9BF8;
	font-weight: bold;
}

.has-meeting .day-number {
	color: #2870E5;
	font-weight: bold;
}

.selected {
	background: #2870E5;
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.4);
}

.selected .day-number {
	color: #fff;
	font-weight: bold;
}

.selected.has-meeting .day-number {
	color: #fff;
}

.meeting-indicators {
	display: flex;
	gap: 4rpx;
	justify-content: center;
	position: absolute;
	bottom: 8rpx;
	left: 50%;
	transform: translateX(-50%);
}

.meeting-dot {
	width: 8rpx;
	height: 8rpx;
	background: #2870E5;
	border-radius: 50%;
	box-shadow: 0 2rpx 4rpx rgba(40, 112, 229, 0.4);
}

.selected .meeting-dot {
	background: #fff;
	box-shadow: 0 2rpx 4rpx rgba(255, 255, 255, 0.4);
}

/* 会议列表 */
.meeting-list {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 40rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.list-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 40rpx;
	padding-bottom: 25rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.date-info {
	flex: 1;
}

.date-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.meeting-count {
	font-size: 24rpx;
	color: #666;
}

.list-actions {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 10rpx;
}

.welcome-text {
	font-size: 24rpx;
	color: #2870E5;
	font-weight: 500;
}

.action-btn {
	min-width: 60rpx;
	height: 60rpx;
	padding: 0 24rpx;
	background: #2870E5;
	color: #fff;
	border-radius: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	font-weight: bold;
	cursor: pointer;
	transition: all 0.3s ease;
	white-space: nowrap;
}

.action-btn:active {
	transform: scale(0.95);
}

.meeting-actions .action-btn {
	width: auto;
	height: auto;
	padding: 12rpx 24rpx;
	border-radius: 8rpx;
	font-size: 26rpx;
	font-weight: 600;
	min-width: 100rpx;
	text-align: center;
}

.meeting-actions .edit-btn {
	background: #2870E5;
	color: #fff;
}

.meeting-actions .edit-btn:active {
	background: #1e5bb8;
}

.meeting-actions .reject-btn {
	background: #ff4d4f;
	color: #fff;
}

.meeting-actions .reject-btn:active {
	background: #d9363e;
}

.meeting-actions .cancel-btn {
	background: #ff9800;
	color: #fff;
}

.meeting-actions .cancel-btn:active {
	background: #f57c00;
}

.meeting-actions .btn-text {
	font-size: 26rpx;
	font-weight: 600;
}

.meeting-items {
	display: flex;
	flex-direction: column;
	gap: 30rpx;
}

.meeting-item {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	padding: 35rpx;
	background: #f8f9fa;
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	transition: all 0.3s ease;
}

.meeting-main {
	cursor: pointer;
	position: relative;
}

.meeting-main:active {
	transform: scale(0.98);
}

.meeting-actions {
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
	padding-top: 20rpx;
	margin-top: 10rpx;
	border-top: 2rpx solid #e8eaed;
}


.meeting-time {
	background: transparent;
	padding-bottom: 20rpx;
	border-radius: 18rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 20rpx;
	margin-bottom: 10rpx;
	box-sizing: border-box;
	position: relative;
}

.time-text {
	font-size: 32rpx;
	font-weight: 700;
	letter-spacing: 1.5rpx;
	color: #2870E5;
	display: block;
	line-height: 1.2;
	position: relative;
	z-index: 1;
}

.meeting-content {
	position: relative;
}

.meeting-header {
	margin-bottom: 20rpx;
}

.meeting-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	line-height: 1.5;
}

.meeting-status {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 22rpx;
	white-space: nowrap;
	flex-shrink: 0;
	font-weight: 600;
	letter-spacing: 0.5rpx;
	transition: all 0.3s ease;
	position: relative;
	z-index: 1;
}


.meeting-status.upcoming {
	background: transparent;
	color: #1890ff;
	border: 1.5rpx solid #1890ff;
}

.meeting-status.ongoing {
	background: transparent;
	color: #fa8c16;
	border: 1.5rpx solid #fa8c16;
}

.meeting-status.completed {
	background: transparent;
	color: #52c41a;
	border: 1.5rpx solid #52c41a;
}

.meeting-status.pending {
	background: transparent;
	color: #ffc107;
	border: 1.5rpx solid #ffc107;
}

.meeting-status.rejected {
	background: transparent;
	color: #ff4d4f;
	border: 1.5rpx solid #ff4d4f;
}

.meeting-status.cancelled {
	background: transparent;
	color: #8c8c8c;
	border: 1.5rpx solid #8c8c8c;
}

.meeting-details {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.detail-item {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.detail-icon {
	width: 24rpx;
	height: 24rpx;
	flex-shrink: 0;
}

.detail-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.6;
}

.meeting-arrow {
	position: absolute;
	right: 0;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	align-items: center;
}

.meeting-arrow image {
	width: 28rpx;
	height: 28rpx;
	opacity: 0.6;
}

/* 加载状态 */
.loading-state {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 80rpx 40rpx;
	text-align: center;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.loading-icon {
	font-size: 60rpx;
	margin-bottom: 20rpx;
	animation: spin 1s linear infinite;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 80rpx 40rpx;
	text-align: center;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.empty-icon {
	font-size: 80rpx;
	margin-bottom: 20rpx;
}

.empty-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 15rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 40rpx;
}

.empty-state .welcome-text {
	font-size: 24rpx;
	color: #2870E5;
	font-weight: 500;
	margin-bottom: 20rpx;
	display: block;
}

.empty-action {
	background: #2870E5;
	color: #fff;
	padding: 20rpx 40rpx;
	border-radius: 25rpx;
	font-size: 28rpx;
	display: inline-block;
	cursor: pointer;
	transition: all 0.3s ease;
}

.empty-action:active {
	transform: scale(0.95);
}
</style> 